﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using Devfw.OpenAuth;

namespace Devfw.OpenAuth.Platform
{
    public class Sina : ProviderBase
    {
        public Sina( string oauth_consumer_key, string oauth_consumer_secret )
            : base( oauth_consumer_key, oauth_consumer_secret )
        {
        }

        public Sina( string oauth_consumer_key, string oauth_consumer_secret, string oauth_token, string oauth_token_secret )
            : base( oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_token_secret )
        {
        }


        #region OAuth
        public RequestTokenResponse request_token()
        {
            return _core.request_token( "http://api.t.sina.com.cn/oauth/request_token");
        }

        public string GetAuthorizeUrl(string  requestToken, string oauth_callback)
        {
            if (!string.IsNullOrEmpty(requestToken))
            {
                return _core.generate_authorize_url("http://api.t.sina.com.cn/oauth/authorize", requestToken, oauth_callback);
            }

            return string.Empty;
        }

        public AccessTokenResponse access_token( string oauth_token, string oauth_token_screct, string oauth_verifier )
        {
            return _core.access_token( "http://api.t.sina.com.cn/oauth/access_token", oauth_token, oauth_token_screct, oauth_verifier );
        }
        #endregion

        #region 微博
        #region 获取微博信息
        public string statuses_get(string format, string blogID)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, 
                string.Format("http://api.t.sina.com.cn/statuses/show/{0}.{1}",blogID, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "id", blogID, ParameterType.Get ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get )
                });

            return response;
        }
        #endregion

        #region 发布微博
        public string statuses_update( string format, string status )
        {
            string response = _core.OpenAuthWebRequest( HttpWebMethod.POST, "http://api.t.sina.com.cn/statuses/update." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "status", HttpUtility.UrlEncode( status ), ParameterType.Post ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Post )
                } );

            return response;
        }

        public string statuses_upload( string format, string status, byte[] imageByte, string fileName )
        {
            var contentEncoding = "iso-8859-1";
            string fileData = System.Text.Encoding.GetEncoding( contentEncoding ).GetString( imageByte );

            string response = _core.OpenAuthFormDataPostWebRequest( "http://api.t.sina.com.cn/statuses/upload." + format, OAuthToken, OAuthTokenSecret,
            new ParameterCollection()
                {
                    new PostParameter( "status", HttpUtility.UrlEncode( status ) ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Post ),
                    new PostParameter( "pic", fileData, true,  "filename=\"" + fileName + "\"", false )
                } );

            return response;
        }

        public string statuses_upload( string format, string status, string url )
        {
            WebClient client = new WebClient();
            byte[] b = client.DownloadData( url );
            string[] f = url.Split( '\\', '/' );
            return statuses_upload( format, status, b, f[f.Length -1] );
        }
        #endregion

        #region 转发微博
        /// <summary>
        /// 转发微博
        /// </summary>
        /// <param name="id">微博id</param>
        /// <param name="status">添加的评论</param>
        /// <param name="is_comment">是否在转发的同时发表评论。0表示不发表评论，1表示发表评论给当前微博，2表示发表评论给原微博，3是1、2都发表。默认为0。</param>
        /// <returns></returns>
        public string StatusesRepost(string format, string id, string status, string is_comment)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, "http://api.t.sina.com.cn/statuses/repost." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "status", HttpUtility.UrlEncode( status ), ParameterType.Post ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "id", id, ParameterType.Get ),
                    new Parameter( "is_comment", is_comment, ParameterType.Get )
                });

            return response;
        }
        #endregion

        #region 评论微博
        /// <summary>
        /// 评论微博
        /// </summary>
        /// <param name="format"></param>
        /// <param name="id">要评论的微博消息ID</param>
        /// <param name="comment">评论内容。必须做URLEncode,信息内容不超过140个汉字。</param>
        /// <param name="commentOri">当评论一条转发微博时，是否评论给原微博。0:不评论给原微博。1：评论给原微博。默认0.</param>
        /// <returns></returns>
        public string StatusesComment(string format, string id, string comment, string commentOri)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, "http://api.t.sina.com.cn/statuses/comment." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "comment", HttpUtility.UrlEncode( comment ), ParameterType.Post ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "id", id, ParameterType.Get ),
                    new Parameter( "without_mention", "0", ParameterType.Get ),
                    new Parameter( "comment_ori", commentOri, ParameterType.Get )
                });

            return response;
        }
        #endregion

        #endregion


        /// <summary>
        /// 是否关注
        /// </summary>
        /// <param name="format"></param>
        /// <param name="useridA"></param>
        /// <param name="useridB"></param>
        /// <returns></returns>
        public bool FriendshipsExists(string format, string TargetUser)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, "http://api.t.sina.com.cn/friendships/show." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "target_screen_name",  TargetUser , ParameterType.Get )
                    
                    
                }, AuthorizationType.UrlQuery);

            xmlHelper help = new xmlHelper(response);
            string ex = help.getValue("/relationship/target/followed_by");
            return ex=="true";
        }

       
        public string getFriendList(string format, string id, string cursor, string count)
        {
            return getFriendList(format, id, "", "", cursor, count);
        }

        public string getFriendList(string format, string id)
        {
            return getFriendList(format, id, "", "", "-1", "200");
        }

        public string statuses_queryid(string format, string mid, int type = 1, int is_batch = 0, int inbox = 0, int isBase62 = 0)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, "http://api.weibo.com/2/statuses/queryid." + format, string.Empty, string.Empty,
                new ParameterCollection()
                {
                    new Parameter( "mid", HttpUtility.UrlEncode( mid ), ParameterType.Get ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "type", type.ToString(), ParameterType.Get ),
                    new Parameter( "isBase62", isBase62.ToString(), ParameterType.Get )
                });

            return response;
        }

        public string statuses_querymid(string format, string id, int type = 1, int is_batch = 0)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, "http://api.weibo.com/2/statuses/querymid." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "id", HttpUtility.UrlEncode( id ), ParameterType.Get ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "type", type.ToString(), ParameterType.Get ),
                });

            return response;
        }



        /// <summary>
        /// 返回好友列表
        /// </summary>
        /// <param name="format">格式</param>
        /// <param name="id">id或昵称</param>
        /// <param name="userid">id</param>
        /// <param name="screen_name">昵称</param>
        /// <param name="cursor">用于分页请求，请求第1页cursor传-1，在返回的结果中会得到next_cursor字段，表示下一页的cursor。next_cursor为0表示已经到记录末尾。</param>
        /// <param name="count">每页返回的最大记录数，最大不能超过200，默认为20。</param>
        /// <returns></returns>
        public string getFriendList(string format, string id, string userid, string screen_name, string cursor, string count)
        {
            if (!string.IsNullOrEmpty(id))
                id = "/" + id;

            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, string.Format("http://api.t.sina.com.cn/statuses/friends{0}.{1}", id, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "user_id", HttpUtility.UrlEncode( userid ), ParameterType.Get ),
                    new Parameter( "screen_name", HttpUtility.UrlEncode( screen_name ), ParameterType.Get ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "cursor", cursor, ParameterType.Get ),
                    new Parameter( "count", count, ParameterType.Get )
                });

            return response;
        }

        public string setSetFriendship(string format,string acttype,string id)
        {

            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sina.com.cn/friendships/{0}.{1}", acttype, format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "screen_name", (id), ParameterType.Get ),

                });

            return response;
        }

        public string getUserShow(string format, string id)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, string.Format("http://api.t.sina.com.cn/users/show.{0}", format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {

                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "user_id",id, ParameterType.Get )
                    
                });

            return response;
        }


        public string getUserShowByScreenName(string format, string screenName)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.GET, string.Format("http://api.t.sina.com.cn/users/show.{0}", format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {

                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "screen_name",screenName, ParameterType.Get )
                    
                });

            return response;
        }



        public string addFriend(string format, string userID)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sina.com.cn/friendships/create.{0}", format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {

                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "user_id",userID, ParameterType.Get )
                    
                });

            return response;
        }


        public string removeFriend(string format, string userID)
        {
            string response = _core.OpenAuthWebRequest(HttpWebMethod.POST, string.Format("http://api.t.sina.com.cn/friendships/destroy.{0}", format), OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {

                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new Parameter( "user_id",userID, ParameterType.Get )
                    
                });

            return response;
        }
        
        /*public string statuses_upload( string format, string status, byte[] imageByte, string fileName )
        {
            var contentEncoding = "iso-8859-1";
            string fileData = System.Text.Encoding.GetEncoding( contentEncoding ).GetString( imageByte );

                string response = _core.OpenAuthFormDataPostWebRequest( "http://api.t.sina.com.cn/statuses/upload." + format, OAuthToken, OAuthTokenSecret,
                new ParameterCollection()
                {
                    new PostParameter( "status", HttpUtility.UrlEncode( status ), "US-ASCII", "text/plain",  "8bit" ),
                    new Parameter( "source", HttpUtility.UrlEncode( _core.OAuthConsumerKey), ParameterType.Get ),
                    new PostParameter( "pic", fileData, "binary", "application/octet-stream", "", "filename=\"" + fileName + "\"", false )
                } );

            return response;
        }*/
    }

}
